// 全局变量
let editingGoalId = null;
let deletingGoalId = null;

// 初始化页面
function initPage() {
    // 初始化储蓄管理器
    const savingsManager = new window.AppData.SavingsManager();
    
    // 刷新储蓄目标列表
    refreshGoalsList();
}

// 刷新储蓄目标列表
function refreshGoalsList() {
    const savingsManager = new window.AppData.SavingsManager();
    const savingsGoals = savingsManager.getSavingsGoals();
    const savingsProgress = savingsManager.getCurrentSavingsProgress();
    
    const goalsListElement = document.getElementById('goalsList');
    const emptyStateElement = document.getElementById('emptyState');
    
    // 没有储蓄目标时显示空状态
    if (savingsGoals.length === 0) {
        goalsListElement.style.display = 'none';
        emptyStateElement.style.display = 'block';
        return;
    }
    
    // 有储蓄目标时隐藏空状态
    goalsListElement.style.display = 'block';
    emptyStateElement.style.display = 'none';
    
    // 构建HTML
    let html = '';
    
    savingsGoals.forEach(goal => {
        // 查找对应的进度
        const progress = savingsProgress.find(p => p.id === goal.id) || {
            percentage: 0,
            savedAmount: 0,
            remaining: goal.targetAmount
        };
        
        // 确定进度条颜色
        let progressClass = 'progress-normal';
        if (progress.percentage >= 50 && progress.percentage < 100) {
            progressClass = 'progress-halfway';
        } else if (progress.percentage >= 100) {
            progressClass = 'progress-complete';
        }
        
        // 获取目标类型文本
        let goalTypeText = '短期目标';
        if (goal.type === 'medium') {
            goalTypeText = '中期目标';
        } else if (goal.type === 'long') {
            goalTypeText = '长期目标';
        }
        
        html += `
            <div class="goal-item">
                <div class="goal-header">
                    <div class="goal-info">
                        <div class="goal-icon">
                            <i class="material-icons">${goal.icon || 'savings'}</i>
                        </div>
                        <div class="goal-name">${goal.name || '储蓄目标'}</div>
                    </div>
                    <div class="goal-actions">
                        <div class="goal-edit" onclick="editGoal('${goal.id}')">
                            <i class="material-icons">edit</i>
                        </div>
                        <div class="goal-delete" onclick="deleteGoal('${goal.id}')">
                            <i class="material-icons">delete</i>
                        </div>
                    </div>
                </div>
                <div class="goal-details">
                    <div class="goal-amount">
                        <div class="amount-label">目标金额</div>
                        <div class="amount-value">¥${goal.targetAmount.toFixed(2)}</div>
                    </div>
                    <div class="goal-amount">
                        <div class="amount-label">已储蓄</div>
                        <div class="amount-value">¥${progress.savedAmount.toFixed(2)}</div>
                    </div>
                    <div class="goal-amount">
                        <div class="amount-label">剩余</div>
                        <div class="amount-value">¥${progress.remaining.toFixed(2)}</div>
                    </div>
                    <div class="goal-amount">
                        <div class="amount-label">完成度</div>
                        <div class="amount-value">${progress.percentage.toFixed(1)}%</div>
                    </div>
                    <div class="goal-amount">
                        <div class="amount-label">储蓄率</div>
                        <div class="amount-value">${goal.savingRate}%</div>
                    </div>
                    <div class="goal-amount">
                        <div class="amount-label">目标类型</div>
                        <div class="amount-value">${goalTypeText}</div>
                    </div>
                    <div class="goal-progress">
                        <div class="progress-bar ${progressClass}" style="width: ${progress.percentage}%"></div>
                    </div>
                </div>
            </div>
        `;
    });
    
    goalsListElement.innerHTML = html;
}

// 打开添加储蓄目标模态框
function openAddGoalModal() {
    document.getElementById('modalTitle').textContent = '添加储蓄目标';
    document.getElementById('goalNameInput').value = '';
    document.getElementById('targetAmountInput').value = '';
    document.getElementById('savingRateInput').value = '';
    document.getElementById('goalTypeSelect').value = 'short';
    document.getElementById('goalIconSelect').value = 'savings';
    editingGoalId = null;
    
    // 显示模态框
    document.getElementById('goalModal').style.display = 'flex';
}

// 打开编辑储蓄目标模态框
function editGoal(goalId) {
    const savingsManager = new window.AppData.SavingsManager();
    const savingsGoals = savingsManager.getSavingsGoals();
    
    const goal = savingsGoals.find(g => g.id === goalId);
    if (!goal) return;
    
    document.getElementById('modalTitle').textContent = '编辑储蓄目标';
    document.getElementById('goalNameInput').value = goal.name || '';
    document.getElementById('targetAmountInput').value = goal.targetAmount;
    document.getElementById('savingRateInput').value = goal.savingRate;
    document.getElementById('goalTypeSelect').value = goal.type || 'short';
    document.getElementById('goalIconSelect').value = goal.icon || 'savings';
    editingGoalId = goalId;
    
    // 显示模态框
    document.getElementById('goalModal').style.display = 'flex';
}

// 关闭模态框
function closeModal() {
    document.getElementById('goalModal').style.display = 'none';
}

// 保存储蓄目标
function saveGoal() {
    const name = document.getElementById('goalNameInput').value.trim();
    const targetAmountInput = document.getElementById('targetAmountInput').value.trim();
    const savingRateInput = document.getElementById('savingRateInput').value.trim();
    const goalType = document.getElementById('goalTypeSelect').value;
    const goalIcon = document.getElementById('goalIconSelect').value;
    
    // 验证
    if (!name) {
        showToast('请输入目标名称', true);
        return;
    }
    
    if (!targetAmountInput || isNaN(targetAmountInput) || parseFloat(targetAmountInput) <= 0) {
        showToast('请输入有效的目标金额', true);
        return;
    }
    
    if (!savingRateInput || isNaN(savingRateInput) || parseFloat(savingRateInput) <= 0 || parseFloat(savingRateInput) > 100) {
        showToast('请输入有效的储蓄率 (1-100)', true);
        return;
    }
    
    const targetAmount = parseFloat(targetAmountInput);
    const savingRate = parseFloat(savingRateInput);
    
    // 初始化储蓄管理器
    const savingsManager = new window.AppData.SavingsManager();
    
    if (editingGoalId) {
        // 编辑现有储蓄目标
        const savingsGoals = savingsManager.getSavingsGoals();
        const index = savingsGoals.findIndex(g => g.id === editingGoalId);
        
        if (index !== -1) {
            const updatedGoal = {
                ...savingsGoals[index],
                name: name,
                targetAmount: targetAmount,
                savingRate: savingRate,
                type: goalType,
                icon: goalIcon
            };
            
            savingsManager.updateSavingsGoal(updatedGoal);
        }
    } else {
        // 添加新储蓄目标
        const newGoal = {
            name: name,
            targetAmount: targetAmount,
            savingRate: savingRate,
            type: goalType,
            icon: goalIcon
        };
        
        savingsManager.addSavingsGoal(newGoal);
    }
    
    // 关闭模态框
    closeModal();
    
    // 刷新储蓄目标列表
    refreshGoalsList();
    
    // 显示成功提示
    showToast(editingGoalId ? '储蓄目标已更新' : '储蓄目标已添加');
}

// 删除储蓄目标
function deleteGoal(goalId) {
    deletingGoalId = goalId;
    document.getElementById('deleteModal').style.display = 'flex';
}

// 关闭删除模态框
function closeDeleteModal() {
    document.getElementById('deleteModal').style.display = 'none';
    deletingGoalId = null;
}

// 确认删除储蓄目标
function confirmDeleteGoal() {
    if (!deletingGoalId) return;
    
    // 初始化储蓄管理器
    const savingsManager = new window.AppData.SavingsManager();
    
    // 删除储蓄目标
    const success = savingsManager.deleteSavingsGoal(deletingGoalId);
    
    if (success) {
        // 关闭模态框
        closeDeleteModal();
        
        // 刷新储蓄目标列表
        refreshGoalsList();
        
        // 显示成功提示
        showToast('储蓄目标已删除');
    } else {
        showToast('删除储蓄目标失败', true);
    }
}

// 显示提示
function showToast(message, isError = false) {
    const toast = document.getElementById('toast');
    toast.textContent = message;
    toast.classList.add('show');
    
    if (isError) {
        toast.classList.add('error');
    } else {
        toast.classList.remove('error');
    }
    
    setTimeout(() => {
        toast.classList.remove('show');
    }, 3000);
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', initPage); 